package spider.service;

import com.htiiot.common.db.DbConnectionPool;
import com.htiiot.common.db.JDBCUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import spider.config.Configs;
import spider.http.HTTPUtil;
import spider.kafka.SendDataToKafka;
import spider.pojo.CharInfos;
import spider.pojo.DeviceStatus;
import spider.pojo.WorkTime;
import spider.pojo.WorkTimeTotal;
import spider.util.JsonUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.List;


public class DeviceWorkTimeService {
    private static Logger logger = LogManager.getLogger(DeviceFailureService.class);
    private static SendDataToKafka sendDataToKafka;
    static{
        sendDataToKafka = new SendDataToKafka();
    }

    public static void updateWorkTime(){
        logger.info("update Work Time");
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        DbConnectionPool pool = DbConnectionPool.getPool();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = pool.getConnection();
            String sql = "select DISTINCT tenant_id tid,name,device_id did from tz_device where tenant_id > 0 AND device_id  > 0";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                DeviceStatus deviceStatus = null;
                String name = rs.getString("name");
                int deviceId = rs.getInt("did");
                int tid = rs.getInt("tid");
                String url = "http://outwardApi.hence.cn/api/EqChart/getDetail?Token=d04259b9c0a3ccabedae048c1d3bef3f&DeviceID="+ name +"&Year="+ year +"&Month="+month;
                logger.info("request updateWorkTime url is : " + url);
                List<WorkTimeTotal> workTimeTotalList = HTTPUtil.get(url, WorkTimeTotal.class);
                if (workTimeTotalList != null && workTimeTotalList.size() > 0) {
                    WorkTimeTotal workTimeTotal = workTimeTotalList.get(0);
                    String rescode = workTimeTotal.getRescode();
                    if ("00".equals(rescode)) {
                        try {
                            deviceStatus = new DeviceStatus();
                            deviceStatus.setTid(tid);
                            deviceStatus.setDid(deviceId);
                            deviceStatus.setTs(System.currentTimeMillis());
                            conn.setAutoCommit(false);
                            String sqlWorkTime = "insert into tz_device_state (device_id,date,work_time,stand_by_time,state) values (?,?,?,?,?) ON DUPLICATE KEY UPDATE work_time = ? , stand_by_time = ? , state = ?";
                            ps = conn.prepareStatement(sqlWorkTime);
                            ps.clearBatch();
                            WorkTime data = workTimeTotal.getData();
                            String state = data.getState();
                            //这里只是改变kafka的数据，MySQL不变
                            if("0".equals(state)){
                                deviceStatus.setSts(1000);
                            }else if("1".equals(state)){
                                deviceStatus.setSts(2000);
                            }else if("2".equals(state)){
                               deviceStatus.setSts(4000);
                            }
                            List<CharInfos> chartInfo = data.getChartInfo();
                            for (int i = 0; i < chartInfo.size(); i++) {
                                CharInfos charInfos = chartInfo.get(i);
                                logger.info("get worktime data is --> "+charInfos);
                                ps.setInt(1, deviceId);
                                ps.setString(2, charInfos.getDatime());
                                ps.setString(3, charInfos.getWorkTime());
                                ps.setString(4, charInfos.getStandbyTime());
                                ps.setString(5, state);
                                ps.setString(6, charInfos.getWorkTime());
                                ps.setString(7, charInfos.getStandbyTime());
                                ps.setString(8, state);
                                ps.addBatch();
                            }
                            ps.executeBatch();
                        } catch (SQLException e) {
                            try {
                                conn.rollback();
                            } catch (SQLException e1) {
                                e1.printStackTrace();
                            }
                            e.printStackTrace();
                        } finally {
                            try {
                                conn.commit();
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                if(deviceStatus != null){
                    sendDataToKafka.send(Configs.KafkaConfig.DEVICESTATUSTOPIC, JsonUtil.buildResult(deviceStatus));
                }
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            JDBCUtils.close(ps, rs, conn);
        }
    }


}
